﻿Imports System.Text.RegularExpressions
Imports System.Reflection
Imports Microsoft.VisualBasic.ApplicationServices
Imports System.IO
Imports System.Threading.Tasks

Public Class frmMain

	Public Delegate Sub UpdateProgressBar(Progress As Integer)
	Public myDelegate As UpdateProgressBar = New UpdateProgressBar(AddressOf UpdateProgressBarMethod)
	Dim SavePath As String

	Private WithEvents myUpdateChecker As New UpdateChecker

	Public Sub btnBeginProcessing_Click(sender As System.Object, e As System.EventArgs) Handles btnBeginProcessing.Click
		Dim SaveFile As FileInfo
		Dim BibleFileName As String = "NWT - " & CType(cmboLanguage.SelectedItem, KeyValuePair(Of String, Translation)).Value.LanguageCode
		Dim BibleName As String = "NWT - " & CType(cmboLanguage.SelectedItem, KeyValuePair(Of String, Translation)).Value.Language

		Try
			With cmboFormat.SelectedItem.ToString
				Select Case True
					Case .Contains("MDB")
						SaveFileDialog1.FileName = BibleFileName & ".bbl"
						SaveFileDialog1.DefaultExt = "bbl"
						SaveFileDialog1.Filter = "bbl files (*.bbl)|*.bbl|All files (*.*)|*.*"
						If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
							DisableUI()
							SaveFile = New FileInfo(SaveFileDialog1.FileName)
							SaveFile.Delete()
							SavePath = SaveFile.DirectoryName
							bgworkerDownloadExport.RunWorkerAsync(New String() {cmboLanguage.SelectedValue, "MDB", SaveFileDialog1.FileName, BibleName})
						End If
					Case .Contains("SQLite")
						SaveFileDialog1.FileName = BibleFileName & ".bblx"
						SaveFileDialog1.DefaultExt = "bblx"
						SaveFileDialog1.Filter = "bblx files (*.bblx)|*.bblx|All files (*.*)|*.*"
						If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
							DisableUI()
							SaveFile = New FileInfo(SaveFileDialog1.FileName)
							SaveFile.Delete()
							SavePath = SaveFile.DirectoryName
							bgworkerDownloadExport.RunWorkerAsync(New String() {cmboLanguage.SelectedValue, "SQLite", SaveFileDialog1.FileName, BibleName})
						End If
				End Select
			End With
		Catch ex As Exception
			btnBeginProcessing.BackgroundImage = My.Resources.XMark
			MessageBox.Show(ex.Message & Environment.NewLine & Environment.NewLine & ex.StackTrace)
		End Try

	End Sub

	Private Sub DisableUI()
		pnlMain.Enabled = False
		btnBeginProcessing.BackgroundImage = My.Resources.Wait
	End Sub

	Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

		cmboLanguage.DataSource = AvailableLanguages.OrderBy(Function(x) x.Value.LanguageCode).ToList
		cmboLanguage.DisplayMember = "Value"
		cmboLanguage.ValueMember = "Key"

		cmboFormat.SelectedItem = "bblx (SQLite)"

		myUpdateChecker.CheckVersion()
		myUpdateChecker.CheckLanguages(AvailableLanguages)
	End Sub

	Private Sub UpdateAvailable(NewVersion As String) Handles myUpdateChecker.UpdateStatus
		lblStatus.Text = "-> " & NewVersion
		lblStatus.LinkArea = New LinkArea(3, lblStatus.Text.Length - 1)
		lblStatus.Enabled = True
	End Sub

	Private Sub NewLanguagesAvailable(NewLangauges As List(Of KeyValuePair(Of String, Translation))) Handles myUpdateChecker.UpdateLangauges
		My.Settings.AvailableLanguages.AvailableLanguages.AddRange(NewLangauges)
	End Sub

	Private Sub lblStatus_LinkClicked(sender As Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lblStatus.LinkClicked
		System.Diagnostics.Process.Start("http://nwtcompiler.codeplex.com/releases")
	End Sub

	Public Sub bgworkerDownloadExport_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgworkerDownloadExport.DoWork
		Dim Arguments() As String = CType(e.Argument, String())
		Dim BibleBaseURL As String = Arguments(0)
		Dim Format As String = Arguments(1)
		Dim FileName As String = Arguments(2)
		Dim BibleName As String = Arguments(3)

		Select Case Format
			Case "MDB"
				ExportToMDBBBL(DownloadBible(BibleBaseURL), BibleBaseURL, FileName, BibleName)
			Case "SQLite"
				ExportToBBLXSQLite(DownloadBible(BibleBaseURL), BibleBaseURL, FileName, BibleName)
		End Select

	End Sub

	Private Sub bgworkerDownloadExport_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgworkerDownloadExport.ProgressChanged
		lblStatus.Text = CType(e.UserState, String)
	End Sub

	Private Sub bgworkerDownloadExport_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgworkerDownloadExport.RunWorkerCompleted
		If e.Error IsNot Nothing Then
			btnBeginProcessing.BackgroundImage = My.Resources.XMark
			MessageBox.Show(e.Error.Message & Environment.NewLine & Environment.NewLine & e.Error.StackTrace)
		Else
			btnBeginProcessing.BackgroundImage = My.Resources.Check
			Process.Start(SavePath)
		End If

		lblStatus.Text = ""

	End Sub

	Public Function DownloadBible(BibleBaseURL As String) As Bible.VersesDataTable
		Dim DownloadedBible As New Bible
		'Dim BookNumber As Integer
		'Dim Chapter As Integer
		'Dim URL As String
		'Dim Page As String

		Parallel.For(1, 67, Sub(BookNumber)
								Dim Chapter As Integer
								Dim URL As String
								Dim Page As String

								Do
									Chapter += 1
									URL = GetNextURL(BookNumber, Chapter, BibleBaseURL)
									Page = GetPage(URL)

									'status update
									bgworkerDownloadExport.ReportProgress(0, URL)

									If Page IsNot Nothing Then
										For Each Verse As KeyValuePair(Of Integer, String) In GetVersesFromPage(Page)
											Dim verseRow As Bible.VersesRow = DownloadedBible.Verses.NewVersesRow

											verseRow.BookNumber = BookNumber
											verseRow.Chapter = Chapter
											verseRow.Verse = Verse.Key
											verseRow.Text = Verse.Value

											DownloadedBible.Verses.AddVersesRow(verseRow)
										Next
									Else
										'reset chapter for next book
										Chapter = 0
									End If
								Loop Until Page Is Nothing
								UpdateProgressBarMethod(BookNumber)
							End Sub)

		Return DownloadedBible.Verses
	End Function

	Public Sub UpdateProgressBarMethod(Progress As Integer)
		If ProgressBar1.InvokeRequired Then
			ProgressBar1.Invoke(myDelegate, New Object() {Progress})
		Else
			'ProgressBar1.Value = Progress
			ProgressBar1.Value += 1
		End If
	End Sub
End Class
